from flask import jsonify
from app.libs.http_api import HttpApi
from flask import current_app


class YushuBook():
    '''
        项目去获取的数据（无论是数据库中还是api中），返回的数据保存类
    '''
    key_api = 'http://127.0.0.1:5000/v1/book/search?key={}&start={}&count={}'
    isbn_api = 'http://127.0.0.1:5000/v1/book/isbn/{}'

    def __init__(self):
        self.books = []
        self.total = 0

    def get_by_key(self, word, page=1):
        url = self.key_api.format(word, self.gain_start(page), current_app.config['PAGE_COUNT'])
        result = HttpApi.get(url)
        self.__fill_collection(result)

    def get_by_isbn(self, isbn):
        url = self.isbn_api.format(isbn)
        result = HttpApi.get(url)
        self.__fill__single(result)

    def __fill__single(self, data):
        if data:
            self.total = 1
            self.books = data

    def __fill_collection(self, data):
        if data:
            self.total = data['total']
            self.books = data['books']

    def gain_start(self, page):
        return (page-1) * current_app.config['PAGE_COUNT']

    @property
    def first(self):
        return self.books[0] if self.total >0 else None